import FileUtil from './FileUtil'
import * as fs from 'fs'
import StrUtil from './StrUtil'

export default class SData {
    static dir = 'D:/html/file/ac/'
    static dataFileUrl = 'D:/html/file/ac/dataFile.json'

    static tempList = [] as any[]

    static init = async () => {
        if (!fs.existsSync(SData.dataFileUrl)) {
            FileUtil.writeFile(SData.dataFileUrl, '[]')
        }
        const _list = await FileUtil.readFile(SData.dataFileUrl)
        SData.tempList = JSON.parse(_list)
    }

    static save = (fileName: string) => {
        SData.tempList.push({
            name: fileName,
            createTime: Date.now()
        })
        FileUtil.writeFile(SData.dataFileUrl, JSON.stringify(SData.tempList))
    }

    static insert = (fileName: string, index?: number): string => {
        const _list = SData.tempList.filter((item) => item.name == fileName)
        const _fileNameIndex = fileName.lastIndexOf('.')
        if (_list.length > 0) {
            const _fn =
                fileName.substring(0, _fileNameIndex) + '-' + StrUtil.uuid() + fileName.substring(_fileNameIndex)
            SData.save(_fn)
            return _fn
        }
        SData.save(fileName)
        return fileName
    }
}
